package org.shangda.wechat.pet.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.shangda.wechat.pet.config.MiniAppProperties;
import org.shangda.wechat.pet.service.WechatMiniappService;
import org.shangda.wechat.pet.util.Constants;
import org.shangda.wechat.pet.util.RedisCacheUtil;
import org.shangda.wechat.pet.util.WxMiniappUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class WechatMiniappServiceImpl implements WechatMiniappService {
    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private MiniAppProperties miniAppProperties;

    @Override
    public String getAccessToken(boolean force){
        String accessToken = redisCacheUtil.get(Constants.YOUNGOR_ZOO_MIINAPP_ACCESSTOKEN);
        if(StringUtils.isBlank(accessToken) || force){
            JSONObject jsonResult = WxMiniappUtil.getAccessToken(miniAppProperties.getAppid(), miniAppProperties.getAppSecret());
            Integer expiresIn = jsonResult.getInteger("expires_in");
            accessToken = jsonResult.getString("access_token");
            redisCacheUtil.refreshValInRedis(Constants.YOUNGOR_ZOO_MIINAPP_ACCESSTOKEN, accessToken, expiresIn * 1000 - 10000);
        }
        return accessToken;
    }

}
